/**
 * Company:湖南省汇聚赢农业开发有限公司
 */

package com.hunhjy.wx.wxsdk;

import java.io.Serializable;
import java.util.Map;

import com.hunhjy.core.kit.RetryUtils.ResultCheck;
import com.hunhjy.wx.wxsdk.util.JsonUtils;

/**
 * @Description: 公众号的全局唯一接口调用凭据access_token
 * @author ZhuoQi_Zou
 * @date 2016年6月25日 下午11:40:04
 *       <li>{"access_token":"ACCESS_TOKEN","expires_in":7200}
 *       <li>{"errcode":40013,"errmsg":"invalid appid"}
 */

public class AccessToken implements ResultCheck, Serializable {

	private static final long serialVersionUID = 6227490935585848353L;
	/** access_token */
	private String access_token; // 正确获取到 access_token 时有值
	/** 有效时间 */
	private Integer expires_in; // 正确获取到
	/** 错误代码 */
	private Integer errcode; // 出错时有值
	/** 错误信息 */
	private String errmsg; // 出错时有值
	/** 存放过期时间 */
	private Long expiredTime; // 正确获取到 access_token 时有值，存放过期时间

	private String json;

	/**
	 * 
	 * @Description: json 更新AccessToken 对象的值
	 * @param jsonStr
	 */
	@SuppressWarnings("unchecked")
	public AccessToken(String jsonStr) {
		this.json = jsonStr;

		try {
			Map<String, Object> temp = JsonUtils.parse(jsonStr, Map.class);
			access_token = (String) temp.get("access_token");
			expires_in = getInt(temp, "expires_in");
			errcode = getInt(temp, "errcode");
			errmsg = (String) temp.get("errmsg");

			if (expires_in != null)
				expiredTime = System.currentTimeMillis() + ((expires_in - 5) * 1000);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 
	 * @Description: access_token 是否有效
	 */
	public boolean isAvailable() {
		if (expiredTime == null)
			return false;
		if (errcode != null)
			return false;
		if (expiredTime < System.currentTimeMillis())
			return false;
		return access_token != null;
	}

	private Integer getInt(Map<String, Object> temp, String key) {
		Number number = (Number) temp.get(key);
		return number == null ? null : number.intValue();
	}

	public Long getExpiredTime() {
		return expiredTime;
	}

	public void setExpiredTime(Long expiredTime) {
		this.expiredTime = expiredTime;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public String getAccess_token() {
		return access_token;
	}

	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}

	public Integer getExpires_in() {
		return expires_in;
	}

	public void setExpires_in(Integer expires_in) {
		this.expires_in = expires_in;
	}

	public Integer getErrcode() {
		return errcode;
	}

	public void setErrcode(Integer errcode) {
		this.errcode = errcode;
	}

	public String getErrmsg() {
		return errmsg;
	}

	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}

	@Override
	public boolean matching() {
		return isAvailable();
	}

}
